<?php

namespace app\admin\model\information;

use app\admin\model\inventory\Wmskc;
use think\Exception;
use think\Model;

class Led extends Model
{
    // 表名
    protected $name = 'led';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    //protected $deleteTime = 'deletetime';
    protected static $colors = [
        'red','blue','green','white','yellow','purple'
    ];
    protected static $colorsName = [
        'red' => '红灯',
        'blue' => '蓝灯',
        'green' => '绿灯',
        'white' => '白灯',
        'yellow' => '黄灯',
        'purple' => '紫灯'
    ];
    protected $type = [
        //'start_time' => 'dateTime'
    ];

    // 追加属性
    protected $append = [
    ];
    
    public function getOutputList()
    {
        return ['on' => __('On'), ' off' => __('OFF')];
    }

    /*public function shelves(){
        return $this->hasOne('\app\common\model\Shelves','id','shelves_id',[],'left')->field('id,name,number')->setEagerlyType(0);
    }

    public function admin(){
        return $this->hasOne('\app\admin\model\Admin','id','uid',[],'left')->field('id,nickname')->setEagerlyType(0);
    }*/
    
    
    public function getOutputTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['output']) ? $data['output'] : '');
        $list = $this->getOutputList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /*
    type=kc、procure、material
    warehousing_code、inv_number、cBatch、uid、warehouse_id、type(kc,in,out)
    */
    public static function setLedOn($data = []){
        if(!$data){
            return ;
        }
        //$inv_number,$uid
        $type = $data['type']??'kc';
        $warehouse_id = $data['warehouse_id']??'';
        $uid = $data['uid']??'';
        $shelves_ids = null;
        if(!$uid){
            return ;
        }

        $inv_number = $data['inv_number']??'';
        $cBatch = $data['cBatch']??'';
        $warehouse_id = $data['warehouse_id']??'';
        $condition = [
            'inv_number' => $inv_number
        ];
        if($cBatch){
            $condition['cBatch'] = $cBatch;
        }

        switch($type){
            case 'kc'://扫库存
            case 'out'://扫出库任务
                if($warehouse_id){
                    $condition['warehouse_id'] = $warehouse_id;
                }
                $shelves_ids = db('wms_kc')->where($condition)
                ->distinct(true)
                ->column('shelves_id');
                break;
            case 'in'://扫入库任务，入库任务最新入库路径
                $warehousing_code = $data['warehousing_code']??'';
                if(!$warehouse_id){
                    return ;
                }
                $condition['warehousing_code'] = $warehousing_code;
                $shelves_ids = db('procure')->where($condition)
                ->distinct(true)
                ->column('lastest_shelves_id');
                break;
        }

        if($shelves_ids){
            return self::lightOn($shelves_ids,$uid);
        }
    }

    //亮灯
    public static function lightOn($shelves_ids,$uid){
        $post_data = Led::getLedDataByShelvesId($shelves_ids);
        trace(['亮灯提交参数',$post_data]);
        if(!$post_data){
            exception('暂无货架LED编码,请先设置货架LED编码');
        }

        //保存亮灯数据，同时关闭之前这个用户的灯
        $check = Led::saveLed($post_data,$uid);
        if(!$check){
            exception('新增灯带数据错误');
        }

        $color = '';
        if($post_data){
            if(in_array($post_data[0]['color'],self::$colors)){
                $color = self::$colorsName[$post_data[0]['color']];
            }
        }
        //调接口post数据
        Led::postLedApi($post_data);
        unset($post_data);
        return $color;
    }

    //灭灯
    public static function lightOff($shelves_ids){
        $post_data = Led::getLedDataByShelvesId($shelves_ids,'OFF');
        trace(['灭灯提交参数',$post_data]);
        
        if($post_data){
            //调接口post数据
            Led::postLedApi($post_data);
            unset($post_data);
        }
    }

    //关闭灯、可全部、可单个客户
    public static function turnOff($uid=''){
        $check = Led::checkApi();
        if($check){
            exception($check);//网络不通
        }

        $condition = [
            'output' => 'on'
        ];

        if($uid){
            $condition['uid'] = $uid;
        }

        $data = db('led')->where($condition)
        ->field("color,'off' output,position")
        ->select();

        if($data){
            //1、调接口关灯
            self::postLedApi($data,$uid);

            //2、关闭本地数据状态
            // self::where($condition)->update([
            //     'output' => 'off'
            // ]);
            self::where($condition)->delete();
        }
    }

    //输入货架，得到要操作开关的，led数组
    public static function getLedDataByShelvesId($shelves_ids = [],$turn_on_off = 'ON'){
        $positions = [];
        $res = [];
        if($shelves_ids){
            $positions = db('shelves')->where([
                'id' => ['IN',$shelves_ids],
                'led_position' => ['NEQ','NOT NULL']
            ])
            ->column('led_position','id');
        }

        $all = self::$colors;
        if($positions){
            $sel_color = '';
            if($turn_on_off=='ON'){
                //获取灯带颜色，排除掉目前亮着的灯带颜色  开灯才需要颜色
                $on_colors = db('led')
                ->where('output','on')
                ->distinct(true)   
                ->column('color');
                $lost = array_diff($all, $on_colors);
                if(!$lost){
                    exception('灯带颜色已被占满,请稍后再试');
                }

                // 随机获取一个键名
                $randomKey = array_rand($lost);
                // 通过键名获取对应的颜色
                $sel_color = $lost[$randomKey];
            }
            
            foreach($positions as $shelves_id=>$position){
                $res[] = [
                    'position' => $position,
                    'output' => $turn_on_off,
                    'color' => $sel_color,
                    'shelves_id' => $shelves_id
                ];
            }
        }
        return $res;
    }

    //保存为本地数据
    public static function saveLed($data = [],$uid = ''){
        if(!$data||!$uid){
            return false;
        }

        Led::turnOff($uid);//先关掉这个用户

        $duringtime = config('site.led_light_duringtime')??60;
        foreach($data as &$item){
            $item['uid'] = $uid;
            $item['start_time'] = time();
            $item['during'] = $duringtime;
        }

        (new self)->saveAll($data);

        return true;
    }

    //判断api接口是否通
    public static function checkApi(){
        // 要 POST 发送的数据
        $postData = [];
        $url = config('site.led_light_api');
        
        // 将数组格式的数据转换为 URL 编码的字符串
        $postDataEncoded = http_build_query($postData);
        // 创建一个 HTTP 上下文流，设置为 POST 请求
        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
                            "Content-Length: " . strlen($postDataEncoded) . "\r\n",
                'content' => $postDataEncoded,
                'timeout' => 2 // 设置超时时间为 1 秒
            ]
        ]);
        // 使用上下文流发送 POST 请求并获取响应
        $msg = '';
        try{
            file_get_contents($url, false, $context);
        }catch(Exception $e){
            trace(['调LED-API:',$e->getMessage()],'error');
            $msg = '调LED-API超时,请检查请求LED地址';
        }
        return $msg;
    }

    //调接口
    public static function postLedApi($data = []){
        $check = Led::checkApi();
        if($check){
            exception($check);//网络不通
        }
        // $data = [
        //     [
        //         "color" => "green",
        //         "output" => "on",
        //         "position" => "0102010101" //01号仓库,02库区(排),01库位(货架,andon编号),01行,01列 "01020101FF"  
        //     ]
        // ];

        if($data){
            self::curl($data);
        }
    }
    
    /**
     * 接口调用
     * @param string $url
     * @param string $postData
     * @param array $headers
     * @return bool|string
     */
    public static function curl($data,$method = 'POST')
    {
        trace(['LED-提交参数',$data],'error');
        
        $ch = curl_init();
        $url = config('site.led_light_api');
        curl_setopt($ch, CURLOPT_URL, $url);
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
        } else {
            curl_setopt($ch, CURLOPT_POST, 0);
        }
        
        //设置头部
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['ZIITEC_ADMIN: ZHIDE0802','Content-Type: application/json']);
        $data = json_encode($data);
        
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); //设置cURL允许执行的最长秒数
        
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $data = curl_exec($ch);
        $data = json_decode($data,true);
        
        if($data){
            if(isset($data['status'])){
                exception("调LED接口失败:".$data['error']);
            }else{
                $res_head = $data['head']??'';
                if($res_head=='SUCCESS_DONE'){
                    //成功
                }else{
                    trace(['调LED接口返回',$data],'error');
                    exception("调LED接口失败");
                }
            }
        }else{
            exception('调LED接口返回空');
        }

        curl_close($ch);
        return $data;
    }
}
